package com.taoym.voucher.xcx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.taoym.voucher.common.constant.RedisKeyConstant;
import com.taoym.voucher.common.response.ResponseStatusCode;
import com.taoym.voucher.common.utils.ExceptionCore;
import com.taoym.voucher.common.utils.SecureUtils;
import com.taoym.voucher.xcx.domain.SysUser;
import com.taoym.voucher.xcx.mapper.SysUserMapper;
import com.taoym.voucher.xcx.service.SysUserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @coder taoym
 * @datetime 2021/7/2 13:15
 * @desc
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public SysUser getSysUser() {
        Object redisObj = redisTemplate.opsForValue().get(RedisKeyConstant.SYS_USER_INFO);
        SysUser sysUser;
        if (!ObjectUtils.isEmpty(redisObj)) {
            sysUser = (SysUser) redisObj;
        } else {
            List<SysUser> sysUsers = sysUserMapper.selectList(new QueryWrapper<>());
            if(CollectionUtils.isEmpty(sysUsers)){
                throw new ExceptionCore(ResponseStatusCode.SYS_DEPLOY_IS_NOT_COMPLETE);
            }
            sysUser = sysUsers.get(0);
            if(ObjectUtils.isEmpty(sysUser.getAppId())||ObjectUtils.isEmpty(sysUser.getAppSecret())){
                throw new ExceptionCore(ResponseStatusCode.SYS_DEPLOY_IS_NOT_COMPLETE);
            }
            redisTemplate.opsForValue().set(RedisKeyConstant.SYS_USER_INFO, sysUser);
        }
        sysUser.setAppId(SecureUtils.decrypt(sysUser.getAppId()));
        sysUser.setAppSecret(SecureUtils.decrypt(sysUser.getAppSecret()));

        return sysUser;
    }
}
